from django.db import models
from django.contrib.auth import get_user_model

User = get_user_model()

class Log(models.Model):
    """
    通用日志模型
    """
    LOG_LEVELS = (
        ('INFO', 'Info'),
        ('WARNING', 'Warning'),
        ('ERROR', 'Error'),
        ('AUDIT', 'Audit'),
    )

    log_type = models.CharField(max_length=20, choices=LOG_LEVELS, default='INFO')  # 日志类型
    user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True, related_name='logs')  # 操作用户
    action = models.CharField(max_length=255)  # 操作描述
    related_object = models.CharField(max_length=255, blank=True, null=True)  # 相关对象描述
    timestamp = models.DateTimeField(auto_now_add=True)  # 日志生成时间
    additional_data = models.JSONField(blank=True, null=True)  # 附加数据，存储额外的信息

    class Meta:
        verbose_name = "Log"
        verbose_name_plural = "Log"
        ordering = ['-timestamp']  # 按时间倒序排列

    def __str__(self):
        return f"[{self.get_log_type_display()}] {self.action} (User: {self.user})"
